package com.ekgc.addressbook.controller;

import antlr.Token;
import com.ekgc.addressbook.base.config.Result;
import com.ekgc.addressbook.base.pojo.vo.TOKEN;
import com.ekgc.addressbook.common.UserInfo;
import com.ekgc.addressbook.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody UserInfo userInfo) {
        try {
            logger.info("接收到用户注册请求，用户名: {}", userInfo.getUserName());
            userService.register(userInfo);
            logger.info("用户注册成功，用户名: {}", userInfo.getUserName());
            return Result.ok();
        } catch (Exception e) {
            logger.error("用户注册失败，用户名: {}, 错误信息: {}", userInfo.getUserName(), e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo) {
        try {
            logger.info("接收到用户登录请求，手机号: {}", userInfo.getPhoneNumber());
            boolean isAuthenticated = userService.login(userInfo.getPhoneNumber(), userInfo.getUserPassword());
            if (isAuthenticated) {
                logger.info("用户登录成功，手机号: {}", userInfo.getPhoneNumber());
                String userId = userService.getUserID(userInfo.getPhoneNumber());
                TOKEN token = new TOKEN(userInfo.getPhoneNumber(),userId);
                return Result.ok(token);
            } else {
                logger.warn("用户登录失败，手机号: {}", userInfo.getPhoneNumber());
                return Result.fail("手机号或密码错误");
            }
        } catch (Exception e) {
            logger.error("用户登录出现异常，手机号: {}, 错误信息: {}", userInfo.getPhoneNumber(), e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }
}